<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Illuminate\Support\Arr;
class Product extends Model
{
    use HasFactory;
    const TYPE_NORMAL = 'normal';
    const TYPE_CROWDFUNDING = 'crowdfunding';
    public static $typeMap = [
        self::TYPE_NORMAL  => '普通商品',
        self::TYPE_CROWDFUNDING => '众筹商品',
    ];
    protected $fillable = [
        'long_title','type',"title","description","image","on_sale","rating","sold_count","review_count","price"
    ];

    protected $casts = [
       "on_sale" => "boolean",//
    ];

    //与商品sku 的关系
    public function skus(){
        return $this->hasMany(ProductSku::class);
    }

    public function getImageUrlAttribute(){
        if(Str::startsWith($this->attributes['image'],["http://","https://"])){
            return $this->attributes["image"];
        }
        return \Storage::disk("public")->url($this->attributes["image"]);
    }
    public function category(){
        return $this->belongsTo(Category::class);
    }

    public function crowdfunding()
    {
        return $this->hasOne(CrowdfundingProduct::class);
    }

    public function properties(){
        return $this->hasMany(ProductProperty::class);
    }
    public function getGroupedPropertiesAttribute()
    {
        return $this->properties
            // 按照属性名聚合，返回的集合的 key 是属性名，value 是包含该属性名的所有属性集合
            ->groupBy('name')
            ->map(function ($properties) {
                // 使用 map 方法将属性集合变为属性值集合
                return $properties->pluck('value')->all();
            });
    }


    //elasticsearch
    public function toESArray(){
        //只取出需要的字段
        $arr = Arr::only($this->toArray(),[
            'id',
            'type',
            'title',
            'category_id',
            'long_title',
            'on_sale',
            'rating',
            'sold_count',
            'review_count',
            'price',
        ]);

        //如果商品有类目，则category字段为类目名数组，否则为空字符串
        $arr['category'] = $this->category() ? explode(" - ",$this->category->full_name) : "";
        //类目的path字段
        $arr['category_path'] = $this->category ? $this->category->path : "";
        //strip_tags函数可以将html标签去除
        $arr['description'] = strip_tags($this->description);
        //只取出需要的sku字段
        $arr['skus'] = $this->skus->map(function (ProductSku $sku) {
            return Arr::only($sku->toArray(), ['title', 'description', 'price']);
        });
        // 只取出需要的商品属性字段
        $arr['properties'] = $this->properties->map(function (ProductProperty $property) {
            return Arr::only($property->toArray(), ['name', 'value']);
        });

        return $arr;
    }
}
